package common

import (
	"bytes"
	"context"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"io/ioutil"
	"mime/multipart"
	"path/filepath"
)

func NewClient() (*oss.Client, error) {
	client, err := oss.New(conf.Endpoint, conf.AccessKeyID, conf.AccessKeySecret)
	return client, err
}

var (
	NearbyBucket = "nearbyuni"
)

func InitOSS() {
	ctx := context.Background()
	conf.Init(ctx)
}

type OSSConfig struct {
	Endpoint        string `json:"endpoint"`
	AccessKeyID     string `json:"access_key_id"`
	AccessKeySecret string `json:"access_key_secret"`
}

var conf = &OSSConfig{}

func (c *OSSConfig) Init(ctx context.Context) {
	conf.Endpoint = "oss-cn-beijing.aliyuncs.com"
	conf.AccessKeyID = "LTAI5tHByRNJYanYvoQmKM4W"
	conf.AccessKeySecret = "UluaRdsyJgKconcFD4x04Zm9wcgGrT"
}

var ImgAllowExts = map[string]bool{
	".jpg":  true,
	".png":  true,
	".gif":  true,
	".jpeg": true,
}

func UploadFile(ctx context.Context, key string, fileHandle multipart.File) error {
	cli, err := NewClient()
	if err != nil {
		return err
	}
	fileByte, err := ioutil.ReadAll(fileHandle) //获取上传文件字节流
	if err != nil {
		return err
	}
	bucket, err := cli.Bucket(NearbyBucket)
	return bucket.PutObject(key, bytes.NewReader(fileByte))
}

func GetUrl(key string) string {
	return "https://cdn.asueeer.com/" + key
}

func IsImage(filename string) bool {
	// 校验图片类型
	fileExt := filepath.Ext(filename)
	if !ImgAllowExts[fileExt] {
		return false
	}
	return true
}
